package com.zuozhj.controller;

import java.security.Principal;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zuozhj.common.Result;
import com.zuozhj.common.dto.RepasswordDTO;
import com.zuozhj.entity.SysUser;

import cn.hutool.core.map.MapUtil;

@RestController
public class AuthController extends BaseController{
    
    @Autowired
    PasswordEncoder passwordEncoder;

    @RequestMapping("/sys/userInfo")
    public Result userInfo(Principal principal) {

        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        
        return Result.success(MapUtil.builder()
            .put("id", sysUser.getId())
            .put("username", sysUser.getUsername())
            .put("avatar", sysUser.getAvatar())
            .map()
        );
    }


    @RequestMapping("/sys/updatePassword")
    public Result updatePassword(@Validated @RequestBody RepasswordDTO repasswordDTO, Principal principal) {

        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        boolean match =  passwordEncoder.matches(repasswordDTO.getCurrentPassword(), sysUser.getPassword());
        
        if (!match) {
            return Result.fail("旧密码不正确");
        }

        sysUser.setPassword(passwordEncoder.encode(repasswordDTO.getPassword()));
        sysUser.setUpdatedAt(LocalDateTime.now());

        sysUserService.updateById(sysUser);

        return Result.success("");
    }
    
}
